package com.glory.dgcpcpda.activity.mfg;

import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.DataBinListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.entity.BinInfoEntity;
import com.glory.dgcpcpda.entity.EqpInfoEntity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * FileName: FTStartTestActivity
 * Author: XJH
 * Date: 2020/6/13 17:27
 * Description: FT开测
 * History:
 */
public class FTStartTestActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etEqpWork)
    FreeUI_ClearEditText etEqpWork;
    @BindView(R.id.tvEqpType)
    TextView tvEqpType;
    @BindView(R.id.tvTestEqp)
    TextView tvTestEqp;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvCustomCode)
    TextView tvCustomCode;
    @BindView(R.id.tvProcesses)
    TextView tvProcesses;
    @BindView(R.id.tvNumber)
    TextView tvNumber;
    @BindView(R.id.tvDataName)
    TextView tvDataName;
    @BindView(R.id.ivDataNameArrow)
    ImageView ivDataNameArrow;
    @BindView(R.id.flDataNameList)
    FrameLayout flDataNameList;
    @BindView(R.id.tvGrading)
    TextView tvGrading;
    @BindView(R.id.ivGradingArrow)
    ImageView ivGradingArrow;
    @BindView(R.id.flGradingList)
    FrameLayout flGradingList;
    @BindView(R.id.rvDataBinList)
    RecyclerView rvDataBinList;
    @BindView(R.id.rvDataNameList)
    RecyclerView rvDataNameList;
    @BindView(R.id.rvGradingList)
    RecyclerView rvGradingList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.cbTestTypeSEQ)
    CheckBox cbTestTypeSEQ;
    private List<DataEntity> mDataNameList;
    private FreeUI_GeneralPop mDataNamePop;
    private DataBinListAdapter mDataBinListAdapter;
    private LotInfoEntity mLoInfoEntity = new LotInfoEntity();
    private FreeUI_GeneralPop mGradingPop;
    private String mStationID = "";
    private List<BinInfoEntity.BinInfo> mRtData;
    private List<BinInfoEntity.BinInfo> mMtData;
    private DataNameAdapter mDataNameAdapter;
    private DataNameAdapter mGradingAdapter;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_start_test_ft;
    }

    @Override
    protected void initView() {
        mDataNameList = new ArrayList<>();
        mRtData = new ArrayList<>();
        mMtData = new ArrayList<>();
        setMainLayout(llMain);
        tvTitle.setText("FT测试在线开测");
        tvGrading.setText("不分档");
        rvDataBinList.setLayoutManager(new GridLayoutManager(this, 2));
        mDataBinListAdapter = new DataBinListAdapter(null, true);
        mDataBinListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mDataBinListAdapter.isFirstOnly(true);
        rvDataBinList.setAdapter(mDataBinListAdapter);
        initRecyclerView(rvDataNameList,this);
        mDataNameAdapter = new DataNameAdapter(R.layout.item_ft_data_bin, mDataNameList, new DataNameAdapter.checkListener() {
            @Override
            public void onCheckListener(String codeS) {
                 if (codeS.equals("RT") | codeS.equals("MT")) {
                     rvDataBinList.setVisibility(View.VISIBLE);
                     mRtData.clear();
                     mMtData.clear();
                     requestBin(codeS);
                 } else {
                     rvDataBinList.setVisibility(View.GONE);
                     mDataBinListAdapter.setNewData(null);
                 }
            }
        });
        initRecyclerView(rvGradingList,this);
        mGradingAdapter = new DataNameAdapter(R.layout.item_ft_data_bin,null,null);
        rvGradingList.setAdapter(mGradingAdapter);
        mDataNameAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mDataNameAdapter.isFirstOnly(true);
        rvDataNameList.setAdapter(mDataNameAdapter);
        initEdit(etLot, s -> LotUtils.searchLotInfo(FTStartTestActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
            @Override
            public void onSuccess(LotInfoEntity response) {
                tvNumber.setText(response.getLOT().getMAINQTY());
                tvCustomCode.setText(response.getLOT().getCUSTOMERCODE());
                tvProcesses.setText(response.getLOT().getSTEPDESC());
                String stepdesc=response.getLOT().getSTEPDESC();
                if(stepdesc.equals("EQC测试")) {
                    tvTitle.setText("EQC测试在线开测");
                }
                mLoInfoEntity = response;
            }

            @Override
            public void onFail(Throwable t) {
                loadError(t, "LOTQUERY");
            }
        }));

        initEdit(etEqpWork, new editTextListener() {
            @Override
            public void onTextChangeListener(String s) {

                FreeUI_EntityCallBack<BaseResponseBean<BinInfoEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<BinInfoEntity>>
                        (new TypeToken<BaseResponseBean<BinInfoEntity>>() {
                        }.getType(), getSupportFragmentManager(), FTStartTestActivity.this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<BinInfoEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().getResponse().getHeader().getRESULT().toUpperCase().equals("FAIL")) {
                            etEqpWork.setText("");
                            showConfirmDialog(response.body().getResponse().getHeader().getRESULTMESSAGE());
                        } else {
                            mDataNameList.clear();
                            String body = response.body().getResponse().getBody().getISTESTTYPE();
                            if (body.equals("N")) {
                                mDataNameList.add(new DataEntity("YP/样品验证"));
                                mDataNameList.add(new DataEntity("QA/抽样"));
                                mDataNameList.add(new DataEntity("FT/初测"));
                                mDataNameList.add(new DataEntity("CT/拆编"));
//                                mDataNameList.add(new DataEntity("FT/初测"));
//                                mDataNameList.add(new DataEntity("CT/拆编"));
//                                mDataNameList.add(new DataEntity("YZ/样品验证"));
//                                mDataNameList.add(new DataEntity("QA/抽样"));
                            }else {
                                mDataNameList.add(new DataEntity("YP/样品验证"));
                                mDataNameList.add(new DataEntity("BC/Bin Check"));
                                mDataNameList.add(new DataEntity("FT/初测"));
                                mDataNameList.add(new DataEntity("QA/抽样"));
                                mDataNameList.add(new DataEntity("RT/复测"));
                                mDataNameList.add(new DataEntity("MT/外观"));
                                mDataNameList.add(new DataEntity("CT/拆编"));
                                mDataNameList.add(new DataEntity("PT/重测"));
//                                mDataNameList.add(new DataEntity("FT/初测"));
//                                mDataNameList.add(new DataEntity("CT/拆编"));
//                                mDataNameList.add(new DataEntity("YZ/样品验证"));
//                                mDataNameList.add(new DataEntity("QA/抽样"));
//                                mDataNameList.add(new DataEntity("RT/复测"));
//                                mDataNameList.add(new DataEntity("MT/外观"));
//                                mDataNameList.add(new DataEntity("BC/Bin Check"));
                            }

                            mDataNameAdapter.setNewData(mDataNameList);
                            rvDataNameList.setVisibility(View.VISIBLE);

                            //请求设备类型、测试机列表
                            LotUtils.searchEqpInfo(s, FTStartTestActivity.this, getSupportFragmentManager(), new LotUtils.netCallback<EqpInfoEntity>() {
                                @Override
                                public void onSuccess(EqpInfoEntity response) {
                                    tvEqpType.setText(response.getEQUIPMENT().getEQPTYPE());
                                    etLot.setText(response.getEQUIPMENT().getLOTID());
                                    if (response.getLISTEQUIPMENT().size() > 0) {
                                        StringBuffer sb = new StringBuffer();
                                        for (EqpInfoEntity.TestEqpEntity entity : response.getLISTEQUIPMENT()){
                                            sb.append(entity.getEQUIPMENTID() + ";");
                                        }
                                        tvTestEqp.setText(sb.toString());
                                        String mGradingMaker = response.getLISTEQUIPMENT().get(0).getGRADINGMARKER();
                                        if (mGradingMaker.equals("0") ||  mGradingMaker.equals("1") || mGradingMaker.equals("")){
                                            rvGradingList.setVisibility(View.GONE);
                                            tvGrading.setVisibility(View.VISIBLE);
                                        }else {
                                            rvGradingList.setVisibility(View.VISIBLE);
                                            tvGrading.setVisibility(View.GONE);
                                            mGradingAdapter.setNewData(getGradingMakerList(mGradingMaker));
                                        }
                                    }

                                    LotUtils.searchLotInfo(FTStartTestActivity.this, response.getEQUIPMENT().getLOTID(), getSupportFragmentManager(),
                                            new LotUtils.netCallback<LotInfoEntity>() {
                                        @Override
                                        public void onSuccess(LotInfoEntity response) {
                                            tvNumber.setText(response.getLOT().getMAINQTY());
                                            tvCustomCode.setText(response.getLOT().getCUSTOMERCODE());
                                            mLoInfoEntity = response;
                                        }

                                        @Override
                                        public void onFail(Throwable t) {
                                            loadError(t, "LOTQUERY");
                                        }
                                    });
                                }

                                @Override
                                public void onFail(Throwable t) {
                                    loadError(t,"EQPQUERY");
                                }
                            });

                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<BinInfoEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(), "EQPTESTSTATUSREQUEST");
                    }
                };
                JsonObject map = new JsonObject();
                map.addProperty("LOTID", getText(etLot));
                map.addProperty("EQUIPMENTID", s);
                NetUtils.requestPostNet("RTM.EQPTESTSTATUSREQUEST", "EQPTESTSTATUSREQUEST", FTStartTestActivity.this,
                        map, callBack);
            }
        });
    }

    @Override
    protected void initData() {

    }


    @OnClick({R.id.tvBaseSubmit, R.id.flDataNameList,R.id.flGradingList,R.id.rbA,R.id.rbB})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                if (actionControl("Submit27")) return;
                String grading;
                if (rvGradingList.getVisibility() == View.GONE) {
                     grading = "不分档";
                }else {
                    if (mGradingAdapter.getDataName().equals("")) {
                        showToast("请选择挡位",false);
                        return;
                    }

                    grading = mGradingAdapter.getDataName();
                }


                if (getText(etLot).equals("") || getText(etEqpWork).equals("")) {
                    showToast("请先扫描批次ID和设备ID", false);
                }else if (mStationID.equals("")){
                    showToast("请选择站别",false);
                }else if (mDataNameAdapter.getDataName().equals("")){
                    showToast("请选择数据命名",false);
                }else {
                    if( mDataNameAdapter.getDataName().split("/")[0].equals("YP")){
                        mDataNameAdapter.setDataName("YZ");
                    }
                    LotUtils.binReport(this, getSupportFragmentManager(), "Test", mDataNameAdapter.getDataName().split("/")[0],
                            getText(etLot), getText(etEqpWork), mLoInfoEntity, mDataBinListAdapter.getItemWork(),grading.equals("不分档") ? "0" : grading,
                            tvEqpType.getText().toString(),tvTestEqp.getText().toString(),mStationID,"STARTTESTSUBMIT","ONLINE",cbTestTypeSEQ.isChecked());
                }

                break;
            case R.id.flDataNameList:
//                if (getText(etLot).equals("") || getText(etEqpWork).equals("")) {
//                    showToast("请先扫描批次ID和设备ID", false);
//                    return;
//                }
//                if (mDataNamePop != null) {
//                    if (mDataNamePop.isShowing()) {
//                        mDataNamePop.dismiss();
//                    }
//                } else {
//                    mDataNamePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flDataNameList.getWidth(), mDataNameList, ivDataNameArrow, (codeS, i) -> {
//                        if (codeS.equals("RT") | codeS.equals("MT")) {
//                            rvDataBinList.setVisibility(View.VISIBLE);
//                            mRtData.clear();
//                            mMtData.clear();
//                            requestBin(codeS);
//                        } else {
//                            rvDataBinList.setVisibility(View.GONE);
//                            mDataBinListAdapter.setNewData(null);
//                        }
//                        tvDataName.setText(codeS);
//                    });
//                }
//                FreeApi_PopUtils.setArrowShow(ivDataNameArrow);
//                mDataNamePop.showAsDropDown(flDataNameList, 0, 0);
                break;
            case R.id.flGradingList:
//                if (mGradingMaker.equals("") || mGradingMaker.equals("不分档")){
//                    return;
//                }
//                if (mGradingPop != null) {
//                    if (mGradingPop.isShowing()) {
//                        mGradingPop.dismiss();
//                    }
//                } else {
//                    mGradingPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flGradingList.getWidth(), getGradingMakerList(), ivGradingArrow, (codeS, i) -> {
//                        tvGrading.setText(codeS);
//                    });
//                }
//                FreeApi_PopUtils.setArrowShow(ivGradingArrow);
//                mGradingPop.showAsDropDown(flGradingList, 0, 0);
                break;
            case R.id.rbA:
                mStationID = "StationA";
                break;
            case R.id.rbB:
                mStationID = "StationB";
                break;

        }
    }

    private List<DataEntity> getGradingMakerList(String mGradingMaker) {
        List<DataEntity> mGradingList = new ArrayList<>();
        for (int i = 1; i <= Integer.parseInt(mGradingMaker); i++) {
            mGradingList.add(new DataEntity(String.valueOf(i)));
        }
        return mGradingList;
    }

    private void requestBin(String testType){
        mMtData.add(new BinInfoEntity.BinInfo("BIN7",""));
        mMtData.add(new BinInfoEntity.BinInfo("BIN8",""));
        mRtData.add(new BinInfoEntity.BinInfo("BIN2",""));
        mRtData.add(new BinInfoEntity.BinInfo("BIN3",""));
        mRtData.add(new BinInfoEntity.BinInfo("BIN4",""));
        mRtData.add(new BinInfoEntity.BinInfo("BIN5",""));
        mRtData.add(new BinInfoEntity.BinInfo("BIN6",""));
        mDataBinListAdapter.setNewData(testType.equals("RT") ? mRtData : mMtData);
    }

    public static class DataNameAdapter extends BaseQuickAdapter<DataEntity, BaseViewHolder>{
        private int index;
        private String dataName = "";
        private checkListener listener;

        public DataNameAdapter(int layoutResId, @Nullable List<DataEntity> data,checkListener listener) {
            super(layoutResId, data);
            this.listener  = listener;
            index = -1;
        }


        @Override
        protected void convert(BaseViewHolder helper, DataEntity item) {
            helper.setText(R.id.checkbox,item.getName());
            CheckBox checkBox = helper.getView(R.id.checkbox);
            checkBox.setChecked(item.isChecked());
            int adapterPosition = helper.getAdapterPosition();
            checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (index == -1){
                        index = adapterPosition;
                        dataName = checkBox.getText().toString();
                        item.setChecked(true);
                    }else if (adapterPosition == index){
                       dataName = "";
                       index = -1;
                       item.setChecked(false);
                    }else if (adapterPosition != index){
                        getData().get(index).setChecked(false);
                        index = adapterPosition;
                        item.setChecked(true);
                        dataName = checkBox.getText().toString();
                    }

                    if (listener != null){
                        listener.onCheckListener(dataName.split("/")[0]);
                    }
                   notifyDataSetChanged();
                }
            });
        }

        public String getDataName() {
            return dataName == null ? "" : dataName;
        }
        public void setDataName(String dataName) {
            this.dataName = dataName;
        }

        public interface checkListener{
            void onCheckListener(String code);
        }
    }

    public static class DataEntity implements Serializable{
        private String name;
        private boolean checked;

        public DataEntity(String name) {
            this.name = name;
        }

        public String getName() {
            return name == null ? "" : name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public boolean isChecked() {
            return checked;
        }

        public void setChecked(boolean checked) {
            this.checked = checked;
        }
    }
}
